package com.angular.useradmin.user.handler.handlerImpl;

import com.angular.useradmin.user.entity.Message;
import com.angular.useradmin.user.entity.New;
import com.angular.useradmin.user.handler.CanalHandler;
import com.angular.useradmin.user.mapper.NewMapper;

import org.springframework.cglib.beans.BeanCopier;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;


@Component
public class CanHandlerImpl implements CanalHandler {

    private final NewMapper newMapper;
    public CanHandlerImpl(NewMapper newMapper) {
        this.newMapper = newMapper;
    }

    /**
     * 类复制
     * @param message
     * @param vo
     */
     private  void toCopy(Message message,New vo){
             BeanCopier.create(Message.class, New.class, false)
                     .copy(message,vo,null);
     }

    /**
     * 数据库插入数据的处理
     * @param message
     */
    @Override
    @Async
    public void insertHandler(Message message) {
        new Thread(() -> {
            New aNew = new New();
            toCopy(message, aNew);
            newMapper.insert(aNew);
        }).start();
    }

    /**
     * 数据库更新数据的处理
     * @param before
     * @param after
     */
    @Override
    @Async
    public void update(Message before, Message after) {
      new Thread(()->{
          New aNew = new New();
          if (!before.getId().equals( after.getId())){
              toCopy(before,aNew);
              newMapper.deleteById(aNew);
              toCopy(after,aNew);
              newMapper.insert(aNew);
          }else{
              toCopy(after,aNew);
              newMapper.updateById(aNew);
          }
      }).start();

    }

    /**
     * 数据库删除数据的处理
     * @param message
     */
    @Override
    @Async
    public void delete(Message message) {
      new Thread(()->{
          New aNew = new New();
          toCopy(message,aNew);
          newMapper.deleteById(aNew);
      }).start();
    }
}
